#include <RenderComponent.h>
#include <EventManager.h>
#include <CoreEvents.h>
#include <Actor.h>
#include <ALEstd.h>
#include <TransformComponent.h>
#include <Scene2D.h>

std::shared_ptr<ISceneNode2D> RenderComponent2D::VGetSceneNode()
{
	if(!m_pSceneNode)
		m_pSceneNode = VCreateSceneNode();
	return m_pSceneNode;
}

void RenderComponent2D::VPostInit()
{
	std::shared_ptr<ISceneNode2D> pNode(VGetSceneNode());
	std::shared_ptr<Event_New_RenderComponent_2D> pEvent(ALE_NEW Event_New_RenderComponent_2D(m_pOwner->GetId(), pNode));
	IEventManager::Get()->VTriggerEvent(pEvent);
}

const char* SpriteComponent::g_name = "SpriteComponent";
const ComponentId& SpriteComponent::g_ID = ActorComponent::GetIdFromName(SpriteComponent::g_name);

bool SpriteComponent::VInit(tinyxml2::XMLElement* pData)
{
	tinyxml2::XMLElement* pFileElement = pData->FirstChildElement("File");
	if(pFileElement)
	{
		const char *pPath = pFileElement->Attribute("path");
		
		wchar_t widePath[64];
		MultiByteToWideChar( CP_ACP, 0, pPath, -1, widePath, 64 );
		widePath[64-1] = 0;

		m_file = std::wstring(widePath);
	}

	return true;
}

std::shared_ptr<ISceneNode2D> SpriteComponent::VCreateSceneNode()
{
	std::weak_ptr<TransformComponent2D> pWeakTrans = m_pOwner->GetComponent<TransformComponent2D>(TransformComponent2D::g_ID);

	if (std::shared_ptr<TransformComponent2D> pTrans = pWeakTrans.lock())
	{
		std::shared_ptr<SpriteNode> pNode;
		Vec2 size = pTrans->GetSize();
		Vec2 pos = pTrans->GetPosition() + size/2;
		pNode.reset(ALE_NEW SpriteNode(m_file.c_str(), &pos, &size, pTrans->GetOrientation(), m_pOwner->GetId()));
		return pNode;
	}
	return std::shared_ptr<ISceneNode2D>();
}

ActorComponent* CreateSpriteComponent()
{
	return ALE_NEW SpriteComponent();
}
